package main

import (
	"io/ioutil"
	"io"
	"bufio"
//	"encoding/json"
	"os"
	"fmt"
	"strings"
	"path/filepath"
	"github.com/bitly/go-simplejson"
)

// VipDomain s
type DomainStruct []struct {
	NsLst []struct {
		Ns string `json:"ns"`
	} `json:"ns_lst"`
	Domain string `json:"domain"`
}

func loadVip() (vipDomainArray []string, vipNsArray []string){
	dat, _ := ioutil.ReadFile("vipdomain/tld/vip_domain_dic")
	js, err := simplejson.NewJson(dat)
	if err != nil {
		panic(err.Error())
	}
	vipDomainDic, _ := js.Map()
//	var vipDomainArray []string
	for domain := range vipDomainDic{
		vipDomainArray = append(vipDomainArray, domain)
	}

	f, err := os.Open("vipdomain/tld/vip_ns_dic")
	js1, err1 := simplejson.NewFromReader(f)
	if err1 != nil {
		panic(err.Error())
	}
//	var vipNsArray []string
	nss, _ := js1.Map()
	for  ns := range nss{
		vipNsArray = append(vipNsArray, ns)
	}
	return 
}

func checkVipSub(lines []string, DomainStruct interface{}, nsStruct interface{}, vipDomainArray []string, vipNsArray[]string)(err error){
	for _, line := range lines{
		if a_type := strings.Split(line, "\t")[2]; a_type != ""{
			if a_type == "NS"{
				fmt.Println(strings.Split(line, "\t")[3])
			}

		}

	}
	return nil
}

func checkVip(domainStruct interface{}, nsStruct interface{}, vipDomainArray []string, vipNsArray []string)(err error){
	lines := []string{}
	filepath.Walk("done", func(path string, info os.FileInfo, err error) error {
//		fmt.Println("Processing: ", path)
		if strings.HasSuffix(path, ".zone"){
			fp, fpOpenErr := os.Open(path)
			if fpOpenErr != nil {
				fmt.Printf("Can not open file %v", fpOpenErr)
				return fpOpenErr
			}
			bReader := bufio.NewReader(fp)
			for {
				line, err := bReader.ReadString('\n')
				if err != nil{
					if err == io.EOF {
						fmt.Printf("File read ok!: %v\n", err)
						break
					} else {
						fmt.Println("File read error!")
					}
				}
				line = line[:len(line)-1]
				if line == "" || strings.HasPrefix(line, ";"){
					continue
				}
				lines = append(lines, line)
				for len(lines) > 500000{
					go checkVipSub(lines[:500000], domainStruct, nsStruct, vipDomainArray, vipNsArray)
					lines = lines[500000:]
				}
			}
		}
		return nil
	})
	fmt.Println("len of lines:", len(lines))
	return nil
}

func main(){
	vipDomainArray, vipNsArray := loadVip()
	domainStruct := map[string][]string{}
	nsStruct := map[string]map[string][]string{}
	checkVip(domainStruct, nsStruct, vipDomainArray, vipNsArray)
//	fmt.Println("len(domainArra):", len(vipDomainArray))
//	fmt.Println("len(vipNsArray):", len(vipNsArray))
}